package com.yun.blog.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yun.blog.bean.QianNiuPutRet;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * title        : QianiuUploadUtils
 * projectName  : dantouBlog-back
 * description  : 七牛上传文件工具类
 * author       : simple
 * email        : yun_simple@163.com
 * date         : 2023/1/16下午5:01
 */

public class QianiuUploadUtils {

    // 七牛云的ACCESS_KEY 和 SECRET_KEY
    private static final String ACCESS_KEY = "kgBeqS6VGFOgQut0x_XMnH3X6ej9DjzWRGPHb56b";
    private static final String SECRET_KEY = "tIJpu1AoK9rKt9c_Pv4Xawsml1Ot2h4LXqYLwA30";
    // 要上传的空间
    private static final String BUCKET_NAME = "dantoublog";

    // 密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static Configuration cfg = new Configuration(Region.xinjiapo());
    // 创建上传对象
    private static UploadManager uploadManager = new UploadManager(cfg);

    // 协议 + 七牛云配置的自定义源站域名
    // 后面在加上回传的key就是文件的访问地址
    private static final String url = "http://img.dantoublog.top/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken() {
        return auth.uploadToken(BUCKET_NAME);
    }

    public static String upload(MultipartFile file, String path) throws IOException {
        try {
            // 得到文件输入流
            InputStream inputStream = file.getInputStream();
            // 得到文件名
            String fileName = UUID.randomUUID() + "-" + file.getOriginalFilename();
            if (path.endsWith("/")) {
                fileName = path + fileName;
            } else {
                fileName = path + "/" + fileName;
            }

            // 调用put方法上传
            Response res = uploadManager.put(inputStream, fileName, getUpToken(), null, null);
            // 打印返回的信息
            System.out.println(res.bodyString());
            QianNiuPutRet qianNiuPutRet = res.jsonToObject(QianNiuPutRet.class);
            return url + qianNiuPutRet.key;

        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }
        return null;
    }

}
